<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Grading Information</title>
    <style>
        body {
            font-family: "Segoe UI", Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
            background-color: #f5f8fa;
            color: #333;
        }

        .container {
            display: flex;
            justify-content: space-between;
            gap: 20px;
            width: 100%;
            max-width: 1600px;
        }

        .panel {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            background-color: white;
            border-radius: 8px;
            padding: 20px;
            box-sizing: border-box;
        }

        .left-panel {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .right-panel {
            flex: 2;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .panel-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            border-bottom: 2px solid #ddd;
            padding-bottom: 5px;
            color: #2c3e50;
        }

        .field {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .field label {
            flex: 1;
            font-weight: bold;
            margin-right: 10px;
            color: #34495e;
        }

        .field input,
        .field select {
            flex: 2;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
            background-color: #f8f9fa;
            color: #555;
            pointer-events: none;
        }

        .attribute-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .attr-btn {
            padding: 8px 15px;
            background-color: #e7e7e7;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
            color: #555;
            transition: all 0.3s;
        }

        .attr-btn.active {
            background-color: #3498db;
            color: white;
        }

        .attributes-container {
            margin-top: 10px;
        }

        .attribute-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }

        .attribute-table th,
        .attribute-table td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }

        .attribute-table th {
            background-color: #f2f2f2;
            font-weight: bold;
            color: #34495e;
        }

        .attribute-table tr.total-row {
            background-color: #e8f4fc;
            font-weight: bold;
        }

        .attribute-name {
            font-weight: bold;
            color: #34495e;
            width: 25%;
        }

        .attribute-description {
            color: #555;
            width: 45%;
        }

        .attribute-value {
            text-align: center;
            width: 15%;
        }

        .attribute-total {
            text-align: center;
            font-weight: bold;
            color: #2980b9;
            width: 15%;
        }

        .switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: 0.4s;
            border-radius: 24px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: 0.4s;
            border-radius: 50%;
        }

        input:checked+.slider {
            background-color: #2196f3;
        }

        input:checked+.slider:before {
            transform: translateX(26px);
        }

        input:disabled+.slider {
            background-color: #ccc;
            cursor: not-allowed;
        }

        input:checked:disabled+.slider {
            background-color: #2196f3;
            opacity: 0.7;
        }

        .number-value {
            font-size: 16px;
            font-weight: bold;
            color: #2980b9;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            margin-top: 10px;
            font-size: 14px;
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
            font-weight: bold;
            color: #34495e;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 15px;
            gap: 10px;
        }

        .pagination-button {
            padding: 5px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #f8f9fa;
            cursor: pointer;
            color: #555;
        }

        .pagination-button:disabled {
            background-color: #e9ecef;
            color: #6c757d;
            cursor: not-allowed;
        }

        .pagination-info {
            font-size: 14px;
            color: #6c757d;
        }

        .no-data {
            text-align: center;
            padding: 20px;
            color: #6c757d;
            font-style: italic;
        }

        .section-title {
            font-size: 16px;
            font-weight: bold;
            margin: 15px 0 10px;
            color: #2c3e50;
            border-bottom: 1px solid #eee;
            padding-bottom: 5px;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #3498db;
        }
    </style>
    <script src="../WebResources/ava_configuration" type="text/javascript"></script>
    <script src="../WebResources/ava_commonutil" type="text/javascript"></script>
    <script>
        window.jsonData = "";
        window.DataId = "";
        window.originalData = "";
        window.UserID = "";
        window.CMSID = "";
    </script>
</head>

<body>
    <div class="container">
        <!-- Left Panel (Grading Value) -->
        <div class="panel left-panel">
            <div class="panel-title">Grading Value</div>

            <div class="field">
                <label for="is-video">Is Video:</label>
                <input type="text" id="is-video" readonly />
            </div>

            <div class="field">
                <label for="is-creator">Is Creator:</label>
                <input type="text" id="is-creator" readonly />
            </div>

            <div class="field">
                <label for="final-decision">Final Decision:</label>
                <input type="text" id="final-decision" readonly />
            </div>

            <div class="field">
                <label for="qualified">Qualified:</label>
                <input type="text" id="qualified" readonly />
            </div>

            <div class="field">
                <label for="reputable">Reputable:</label>
                <input type="text" id="reputable" readonly />
            </div>

            <div class="field">
                <label for="recognizable">Recognizable:</label>
                <input type="text" id="recognizable" readonly />
            </div>

            <div class="field">
                <label for="grade-date">Grade Date:</label>
                <input type="text" id="grade-date" readonly />
            </div>
        </div>

        <!-- Right Panel (Grading Attributes) -->
        <div class="panel right-panel">
            <div class="panel-title">Grading Attributes</div>

            <!-- Attribute Type Selector -->
            <div class="attribute-buttons">
                <button class="attr-btn active" data-type="acceptable">
                    Acceptable Attributes
                </button>
                <button class="attr-btn" data-type="reputable">
                    Reputable Attributes
                </button>
                <button class="attr-btn" data-type="recognizable">
                    Recognizable Attributes
                </button>
            </div>

            <!-- Attributes Container -->
            <div id="attributesContainer" class="attributes-container">
                <!-- Attributes will be dynamically rendered here -->
            </div>

            <!-- Audit History -->
            <div class="section-title">Audit History</div>
            <table id="auditTable">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Field</th>
                        <th>Old</th>
                        <th>New</th>
                        <th>Editor</th>
                    </tr>
                </thead>
                <tbody id="auditTableBody">
                    <tr>
                        <td colspan="5" class="loading">Loading audit history...</td>
                    </tr>
                </tbody>
            </table>

            <!-- Pagination Controls -->
            <div class="pagination">
                <button id="prevPage" class="pagination-button" disabled>
                    Previous
                </button>
                <span id="pageInfo" class="pagination-info">Page 1 of 1</span>
                <button id="nextPage" class="pagination-button" disabled>Next</button>
            </div>
        </div>
    </div>

    <script>
        Xrm = window.parent.Xrm;
        brandID = Xrm.Page.data.entity
            .getId()
            .replace(/[\{\}]*/g, "")
            .toLowerCase();
        var UserId = window.parent.Xrm.Page.context.getUserId();
        UserId = UserId.replace(/[\{\}]*/g, "").toLowerCase();

        String.prototype.format = function () {
            var args = arguments;
            return this.replace(/{(\d+)}/g, function (match, number) {
                return typeof args[number] != "undefined" ? args[number] : match;
            });
        };
        //load brand
        var FetchXmlStringBrand = `<fetch top="50">
  <entity name="ava_brand">
    <attribute name="ava_brandstatus" />
    <attribute name="ava_cmsbrandid" />
    <filter>
      <condition attribute="ava_brandid" operator="eq" value="{0}" />
    </filter>
    <link-entity name="ava_cmspartner" from="ava_cmspartnerid" to="ava_cmspartnerid" link-type="outer" alias="Partner">
      <attribute name="ava_partnerterminatestatus" />
    </link-entity>
  </entity>
</fetch>`;
        fetch(
            `/api/data/v9.1/ava_brands?fetchXml=${encodeURI(
                FetchXmlStringBrand.format(brandID)
            )}`,
            {
                headers: {
                    "Content-Type": "application/json",
                    Prefer: 'odata.include-annotations="*"',
                },
            }
        )
            .then((resault) => resault.json())
            .then((resault) => {
                console.log(resault, "BrandResault");

                // 调用 API 并保存返回的数据
                var cmsID = resault.value[0].ava_cmsbrandid;
                console.log(cmsID, "cmsID");
                CMSID = cmsID;
                let pdpData;
                var gradingData = {};
            })
            .catch((err) => {
                console.log(err, "BrandErr");
            });
        // TODO: Replace this with actual API response
        const apiResponse = [
            {
                brandId: "AAqcK7",
                brandEvaluationResult: {
                    acceptable: true,
                    reputable: "High",
                    recognizable: "High",
                    reputableScore: 60,
                    recognizableScore: 50,
                    brandProfileSnapshotJSON: "",
                    evaluationResultJSON: JSON.stringify({
                        BrandAcceptableAttributes: {
                            primaryMarketAlignment: true,
                            aigcByline: false,
                            noMisinformation: true,
                            consistency: true,
                            publishingGuidelines: true,
                        },
                        BrandReputableAttributes: {
                            establishedHistory: 4,
                            originalWork: 3,
                            industryAwards: 2,
                            notablePersonalities: 3,
                            domainExpertise: 4,
                            citations: 3,
                            collaborationEndorsements: 2,
                            engagement: 4,
                            community: 3,
                        },
                        BrandRecognizableAttributes: {
                            familiarity: 3,
                            multiPlatformPresence: 4,
                            notablePersonalities: 3,
                            followership: 4,
                            socialMediaActivity: 3,
                        },
                    }),
                    resultTimeStampUTC: "2025-08-11T02:41:37.1395164Z",
                    adoWorkItemId: 0,
                    gradingContentType: 0,
                },
                isVideo: true,
                isCreator: false,
            },
        ];

        // field display name mapping
        const attributeDisplayNames = {
            // Acceptable Attributes
            primaryMarketAlignment: "Primary Market Alignment",
            aigcByline: "AIGC Byline",
            noMisinformation: "No Misinformation",
            consistency: "Consistency",
            publishingGuidelines: "Publishing Guidelines",

            // Reputable Attributes
            establishedHistory: "Established History",
            originalWork: "Original Work",
            industryAwards: "Industry Awards",
            notablePersonalities: "Notable Personalities",
            domainExpertise: "Domain Expertise",
            citations: "Citations",
            collaborationEndorsements: "Collaboration Endorsements",
            engagement: "Engagement",
            community: "Community",

            // Recognizable Attributes
            familiarity: "Familiarity",
            multiPlatformPresence: "Multi-Platform Presence",
            followership: "Followership",
            socialMediaActivity: "Social Media Activity",
        };

        // field description mapping
        const attributeDescriptions = {
            // Reputable Attributes
            establishedHistory:
                "Score for established history, applicable to news and non-news brands",
            originalWork: "Score for established history, applicable to all brands",
            industryAwards: "Score for industry awards, applicable to news brands",
            notablePersonalities:
                "Score for notable personalities, applicable to news brands",
            domainExpertise: "Score for domain expertise, applicable to all brands",
            citations: "Score for citations, applicable to non-news brands",
            collaborationEndorsements:
                "Score for Collaboration and Endorsements, applicable to non-news and Video brands",
            engagement: "Score for engagement, applicable to Video brands",
            community: "Score for community, applicable to Video brands",

            // Recognizable Attributes
            familiarity:
                "Score for familiarity, applicable to news and non-news brands",
            multiPlatformPresence:
                "Score for multi-platform presence, applicable to all brands",
            notablePersonalities:
                "Score for notable personalities, applicable to news and non-news brands",
            followership: "Score for followship, applicable to all brands",
            socialMediaActivity:
                "Score for Social Medium activity, applicable to video brands",
        };

        // String format
        String.prototype.format = function () {
            var args = arguments;
            return this.replace(/{(\d+)}/g, function (match, number) {
                return typeof args[number] != "undefined" ? args[number] : match;
            });
        };

        // extract and process API data
        function processApiData(apiData) {
            try {
                const item = apiData[0] || {};
                const ber = item.brandEvaluationResult || {};
                let evaluationResult = {};
                if (ber.evaluationResultJSON && typeof ber.evaluationResultJSON === 'string') {
                    try {
                        evaluationResult = JSON.parse(ber.evaluationResultJSON);
                    } catch (e) {
                        evaluationResult = {};
                    }
                }
                return {
                    isVideo: item.isVideo === true ? "Yes" : (item.isVideo === false ? "No" : "null"),
                    isCreator: item.isCreator === true ? "Yes" : (item.isCreator === false ? "No" : "null"),
                    finalDecision: ber.acceptable === true ? "Accept" : (ber.acceptable === false ? "Reject" : ""),
                    qualified: ber.acceptable === true ? "Yes" : (ber.acceptable === false ? "No" : ""),
                    reputable: ber.reputable != null ? ber.reputable : "",
                    recognizable: ber.recognizable != null ? ber.recognizable : "",
                    gradeDate: ber.resultTimeStampUTC ? formatDate(ber.resultTimeStampUTC) : "",
                    acceptableAttributes: (evaluationResult.BrandAcceptableAttributes && typeof evaluationResult.BrandAcceptableAttributes === 'object') ? evaluationResult.BrandAcceptableAttributes : {},
                    reputableAttributes: (evaluationResult.BrandReputableAttributes && typeof evaluationResult.BrandReputableAttributes === 'object') ? evaluationResult.BrandReputableAttributes : {},
                    recognizableAttributes: (evaluationResult.BrandRecognizableAttributes && typeof evaluationResult.BrandRecognizableAttributes === 'object') ? evaluationResult.BrandRecognizableAttributes : {},
                    reputableScore: (typeof ber.reputableScore === 'number' && !isNaN(ber.reputableScore)) ? ber.reputableScore : 0,
                    recognizableScore: (typeof ber.recognizableScore === 'number' && !isNaN(ber.recognizableScore)) ? ber.recognizableScore : 0
                };
            } catch (error) {
                console.error("Error processing API data:", error);
                return {};
            }
        }

        // format date to readable string
        function formatDate(dateString) {
            if (!dateString) return "";
            const date = new Date(dateString);
            return date.toLocaleDateString("en-US", {
                year: "numeric",
                month: "short",
                day: "numeric",
            });
        }

        let editEnable = false;

function GetBrandRoleName(roleId) {
  var req = new XMLHttpRequest();
  var roleName = null;

  req.open(
    "GET",
    Xrm.Utility.getGlobalContext().getClientUrl() +
      "/api/data/v9.1/roles(" +
      roleId +
      ")?$select=name",
    false
  );
  req.setRequestHeader("OData-MaxVersion", "4.0");
  req.setRequestHeader("OData-Version", "4.0");
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.setRequestHeader("Prefer", 'odata.include-annotations="*"');
  req.onreadystatechange = function () {
    if (this.readyState === 4) {
      req.onreadystatechange = null;
      if (this.status === 200) {
        var result = JSON.parse(this.response);
        roleName = result["name"];
      } else {
        alert(this.statusText);
      }
    }
  };
  req.send();

  return roleName;
}
        // check user permission
        function checkEditPermission() {
            var context = Xrm.Utility.getGlobalContext();
            var currentUserRoles = context.userSettings.securityRoles;
            // const currentUserRoles = ["PM", "OtherRole"];
            const allowedRoles = [
                "PM",
                "System Administrator",
                "BizDev",
                "System Administrator - STCA",
                "BizDev - STCA",
            ];
            for (let i = 0; i < currentUserRoles.length; i++) {
                var roleName = GetBrandRoleName(currentUserRoles[i]);
                if (allowedRoles.includes(roleName)) {
                    return true;
                }
            }
            return false;
        }

        // left box fields 配置
        const leftPanelFields = [
            { key: "isVideo", label: "Is Video" },
            { key: "isCreator", label: "Is Creator" },
            { key: "finalDecision", label: "Final Decision" },
            { key: "qualified", label: "Qualified" },
            { key: "reputable", label: "Reputable" },
            { key: "recognizable", label: "Recognizable" },
            { key: "gradeDate", label: "Grade Date" }
        ];

        // left box render (动态)
        function renderLeftPanel(data) {
            const leftPanel = document.querySelector('.left-panel');
            // 保留标题
            leftPanel.innerHTML = '<div class="panel-title">Grading Value</div>';
            leftPanelFields.forEach(field => {
                const fieldDiv = document.createElement('div');
                fieldDiv.className = 'field';
                const label = document.createElement('label');
                label.setAttribute('for', field.key);
                label.textContent = field.label + ':';
                const input = document.createElement('input');
                input.type = 'text';
                input.id = field.key;
                input.value = data[field.key] || '';
                input.readOnly = !editEnable;
                input.disabled = !editEnable;
                input.style.pointerEvents = editEnable ? 'auto' : 'none';
                fieldDiv.appendChild(label);
                fieldDiv.appendChild(input);
                leftPanel.appendChild(fieldDiv);
            });
        }

        // attributes render
        function renderAttributes(attributes, type) {
            const container = document.getElementById("attributesContainer");
            container.innerHTML = "";
            if (!attributes || Object.keys(attributes).length === 0) {
                container.innerHTML =
                    '<div class="no-data">No attributes available</div>';
                return;
            }
            const table = document.createElement("table");
            table.className = "attribute-table";
            const thead = document.createElement("thead");
            if (type === "acceptable") {
                thead.innerHTML = `
                    <tr>
                        <th>Attribute</th>
                        <th>Value</th>
                    </tr>
                `;
            } else {
                thead.innerHTML = `
                    <tr>
                        <th>Attribute</th>
                        <th>Description</th>
                        <th>Value</th>
                    </tr>
                `;
            }
            table.appendChild(thead);
            const tbody = document.createElement("tbody");
            let totalScore = 0;
            for (const [key, value] of Object.entries(attributes)) {
                const row = document.createElement("tr");
                const nameCell = document.createElement("td");
                nameCell.className = "attribute-name";
                nameCell.textContent = attributeDisplayNames[key] || key;
                row.appendChild(nameCell);
                if (type === "acceptable") {
                    const valueCell = document.createElement("td");
                    valueCell.className = "attribute-value";
                    valueCell.innerHTML = `
                        <label class="switch">
                            <input type="checkbox" ${value ? "checked" : ""} ${editEnable ? "" : "disabled"
                        }>
                            <span class="slider"></span>
                        </label>
                    `;
                    row.appendChild(valueCell);
                } else {
                    const descCell = document.createElement("td");
                    descCell.className = "attribute-description";
                    descCell.textContent = attributeDescriptions[key] || "";
                    row.appendChild(descCell);
                    const valueCell = document.createElement("td");
                    valueCell.className = "attribute-value";
                    if (editEnable) {
                        valueCell.innerHTML = `<input type="number" value="${value}" min="0" max="5">`;
                    } else {
                        const numberSpan = document.createElement("span");
                        numberSpan.className = "number-value";
                        numberSpan.textContent = value;
                        valueCell.appendChild(numberSpan);
                    }
                    row.appendChild(valueCell);
                    totalScore += Number(value) || 0;
                }
                tbody.appendChild(row);
            }
            // add total score row for reputable and recognizable attributes
            if (type !== "acceptable") {
                const totalRow = document.createElement("tr");
                totalRow.className = "total-row";
                totalRow.innerHTML = `
                    <td colspan="2" style="text-align: right;">Total Score</td>
                    <td class="attribute-total">${totalScore}</td>
                `;
                tbody.appendChild(totalRow);
            }
            table.appendChild(tbody);
            container.appendChild(table);
        }

        // setup attribute buttons
        function setupAttributeButtons(data) {
            const buttons = document.querySelectorAll(".attr-btn");
            buttons.forEach((button) => {
                button.addEventListener("click", () => {
                    // Remove active class from all buttons
                    buttons.forEach((btn) => btn.classList.remove("active"));
                    // Add active class to clicked button
                    button.classList.add("active");

                    const type = button.dataset.type;
                    switch (type) {
                        case "acceptable":
                            renderAttributes(data.acceptableAttributes, type);
                            break;
                        case "reputable":
                            renderAttributes(data.reputableAttributes, type);
                            break;
                        case "recognizable":
                            renderAttributes(data.recognizableAttributes, type);
                            break;
                    }
                });
            });
        }

        // Pagination variables
        let currentPage = 1;
        const itemsPerPage = 5;
        let auditHistoryData = [];

        // Load audit history data
        function loadAuditHistory() {
            const FetchXmlString = `<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true" returntotalrecordcount="true" no-lock="false">
                    <entity name="{0}">
                        <all-attributes/>
                        <filter type="and">
                            <condition attribute="{1}" operator="in">
                                <value>{2}</value>
                            </condition>
                            <condition attribute="{3}" operator='eq' value="{4}"/>
                            <condition attribute="ava_iscrossmarket" operator="ne" value="1" />
                        </filter>
                        <order attribute="ava_changedate" descending="true" />
                    </entity>
                </fetch>`;

            //tODO: Replace this with actual API call
            fetch(
                `/api/data/v9.1/ava_table1s?fetchXml=${encodeURI(
                    FetchXmlString.format(
                        "ava_table1",
                        "ava_tablelogicname",
                        "ava_brand",
                        "ava_dataid",
                        brandID
                    )
                )}`,
                {
                    headers: {
                        "Content-Type": "application/json",
                        Prefer: 'odata.include-annotations="*"',
                    },
                }
            )
               .then((res) => res.json()) .then((res) => {
                    const tableBody = document.getElementById("auditTableBody");
                    tableBody.innerHTML = "";

                    if (!res.value || res.value.length === 0) {
                        tableBody.innerHTML =
                            '<tr><td colspan="5" class="no-data">No audit history available</td></tr>';
                        return;
                    }

                    auditHistoryData = [];

                    for (var i in res.value) {
                        const loadData = JSON.parse(res.value[i].ava_changes);
                        loadData.forEach((record) => {
                            const changes = JSON.parse(record.changes);
                            changes.forEach((change) => {
                                auditHistoryData.push({
                                    date: record.date,
                                    field: change.field,
                                    old: JSON.stringify(change.old.value),
                                    new: JSON.stringify(change.new.value),
                                    editor:
                                        res.value[i][
                                        "_createdby_value@OData.Community.Display.V1.FormattedValue"
                                        ] || "Unknown",
                                });
                            });
                        });
                    }

                    renderAuditHistory();
                    setupPagination();
                })
                .catch((err) => {
                    console.error("Error loading audit history:", err);
                    document.getElementById("auditTableBody").innerHTML =
                        '<tr><td colspan="5" class="no-data">Error loading audit history</td></tr>';
                });
        }

     

        // Render audit history table based on current page
        function renderAuditHistory() {
            const tableBody = document.getElementById("auditTableBody");
            tableBody.innerHTML = "";

            const startIndex = (currentPage - 1) * itemsPerPage;
            const endIndex = Math.min(
                startIndex + itemsPerPage,
                auditHistoryData.length
            );

            if (auditHistoryData.length === 0) {
                tableBody.innerHTML =
                    '<tr><td colspan="5" class="no-data">No audit history available</td></tr>';
                return;
            }

            for (let i = startIndex; i < endIndex; i++) {
                const item = auditHistoryData[i];
                const row = document.createElement("tr");

                row.innerHTML = `
                    <td>${item.date}</td>
                    <td>${item.field}</td>
                    <td>${item.old}</td>
                    <td>${item.new}</td>
                    <td>${item.editor}</td>
                `;

                tableBody.appendChild(row);
            }

            updatePaginationInfo();
        }

        function updatePaginationInfo() {
            const totalPages = Math.ceil(auditHistoryData.length / itemsPerPage);
            document.getElementById(
                "pageInfo"
            ).textContent = `Page ${currentPage} of ${totalPages}`;

            // Enable/disable buttons
            document.getElementById("prevPage").disabled = currentPage === 1;
            document.getElementById("nextPage").disabled =
                currentPage === totalPages || totalPages === 0;
        }

        function setupPagination() {
            document.getElementById("prevPage").addEventListener("click", () => {
                if (currentPage > 1) {
                    currentPage--;
                    renderAuditHistory();
                }
            });

            document.getElementById("nextPage").addEventListener("click", () => {
                const totalPages = Math.ceil(auditHistoryData.length / itemsPerPage);
                if (currentPage < totalPages) {
                    currentPage++;
                    renderAuditHistory();
                }
            });
        }

        // Fetch API response with retry logic
        async function fetchApiResponse() {
            await ConfigurationOpt.InitGlobalConfigurationPromise();
            var url = ConfigurationOpt.GetConfigurationValueSync(
                ConfigurationOpt.ConfigurationKeys.PDPBrandGradingReadLink
            );
            var ocid = ConfigurationOpt.GetConfigurationValueSync(
                ConfigurationOpt.ConfigurationKeys.PDPBrandGradingOcid
            );
            url = url + CMSID + "&" + ocid;
            // url = url.replace("{ocid}", ocid);
            var maxRetries = 3;
            var attempt = 0;
            var lastErrorCode = null;
            return new Promise((resolve, reject) => {
                function sendRequest() {
                    var req = new XMLHttpRequest();
                    req.open("GET", url, true);
                    req.setRequestHeader("Accept", "application/json");
                    req.setRequestHeader(
                        "Content-Type",
                        "application/json; charset=utf-8"
                    );
                    req.onreadystatechange = function () {
                        if (this.readyState == 4) {
                            req.onreadystatechange = null;
                            if (this.status == 200) {
                                try {
                                    var resp = JSON.parse(this.responseText);
                                    resolve(resp);
                                } catch (e) {
                                    lastErrorCode = "解析错误";
                                    reject(lastErrorCode);
                                }
                            } else if (this.status == 412 && attempt < maxRetries) {
                                attempt++;
                                lastErrorCode = this.status;
                                setTimeout(sendRequest, 200);
                            } else {
                                lastErrorCode = this.status;
                                reject(lastErrorCode);
                            }
                        }
                    };
                    req.send();
                }
                sendRequest();
            });
        }

        function showApiError(code) {
            let container = document.getElementById("attributesContainer");
            if (container) {
                container.innerHTML = `<div style='color:red;font-weight:bold;padding:20px;'>API Request error ，StatusCode：${code}<br>please contact bdtprod@microsoft.com</div>`;
            }
        }

        document.addEventListener("DOMContentLoaded", async function () {
            // 权限判断
            editEnable = checkEditPermission();
            // 异步获取API数据并渲染
            try {
                // const apiResponse = await fetchApiResponse();
                const processedData = processApiData(apiResponse);
                renderLeftPanel(processedData);
                renderAttributes(processedData.acceptableAttributes, "acceptable");
                setupAttributeButtons(processedData);
            } catch (err) {
                showApiError(err);
                console.error("API数据获取失败", err);
            }
            loadAuditHistory();
        });
    </script>
</body>

</html>